package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    //自己的minIO
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
/**        //检查参数：
 if (multipartFile == null) {
 return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
 }

 //图片上传minIO，返回URL
 //文件名
 String imgName = UUID.randomUUID().toString();
 //后缀名：
 String originalFilename = multipartFile.getOriginalFilename();
 //截取获取后缀名
 String latName = originalFilename.substring(originalFilename.lastIndexOf("."));
 //上传
 String path = null ;
 try {
 path = fileStorageService.uploadImgFile("", imgName + latName, multipartFile.getInputStream());
 log.info("文件上传成功:{}", path);
 } catch (IOException e) {
 e.printStackTrace();
 log.error("文件上传失败");
 }

 //保存数据到数据库
 WmMaterial wmMaterial = WmMaterial.builder()
 .createdTime(new Date())
 .isCollection((short) 0)
 .userId(WmThreadLocalUtils.getUser().getId())
 .type((short) 0)
 .url(path)
 .build();
 save(wmMaterial);

 //返回
 return ResponseResult.okResult(wmMaterial);
 **/

        //1：检查参数：
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2：将图片上传到minIO中
        //2.1：创建文件名：
        String uuid = UUID.randomUUID().toString();
        //2.2：获取文件后缀 .jpg
        String originalFilename = multipartFile.getOriginalFilename();
        //字符串截取：以 .  截取
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String path = "";
        try {
            //上传： 第二个参数上传后的文件名称 第三个文件输入流：
            path = fileStorageService.uploadImgFile("", uuid + postfix, multipartFile.getInputStream());
            log.info("上传成功:{}", path);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传失败");
        }

        //将图片路径放入数据库中
        WmMaterial wmMaterial = WmMaterial.builder()
                .createdTime(new Date())
                .isCollection((short) 0)
                .userId(WmThreadLocalUtils.getUser().getId())
                .type((short) 0)
                .url(path)
                .build();
        save(wmMaterial);
        //返回结果
        return ResponseResult.okResult(wmMaterial);

    }


    /**
     * 图片列表查看
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //校验参数：用父类中的方法：
        dto.checkParam();

        //构建分页查询：
        //分页查询：
        IPage page = new Page(dto.getPage(), dto.getSize());
        //条件：
        LambdaQueryWrapper<WmMaterial> lqw = Wrappers.<WmMaterial>lambdaQuery()
                //根据当前登录的用户ID查询
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                //根据时间倒序排序
                .orderByDesc(WmMaterial::getCreatedTime);
        //是否为收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lqw.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //待条件查询：
        page = page(page, lqw);

        //返回数据：
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        result.setCode(200);
        return result;
    }
}
